﻿using Furion.CMS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.EntityFramework.Core
{
    public static class CollectionExtension
    {
        /// <summary>
        /// 集合变更
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="self"></param>
        /// <param name="target"></param>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        public static ICollection<TEntity> ToCollectionChange<TEntity, TKey>(this ICollection<TEntity> self, IEnumerable<TEntity> target, Func<TEntity, TKey> keySelector)
        {
            List<TEntity> insertItems,
                removeItems;
            return ToCollectionChange(self, target, keySelector, out insertItems, out removeItems);
        }

        /// <summary>
        /// 集合变更
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="self"></param>
        /// <param name="target"></param>
        /// <param name="keySelector"></param>
        /// <param name="insertItems"></param>
        /// <param name="removeItems"></param>
        /// <returns></returns>
        public static ICollection<TEntity> ToCollectionChange<TEntity, TKey>(this ICollection<TEntity> self, IEnumerable<TEntity> target, Func<TEntity, TKey> keySelector,
            out List<TEntity> insertItems, out List<TEntity> removeItems)
        {
            insertItems = target.ExceptBy(self.Select(keySelector), keySelector).ToList();
            insertItems.ForEach(a => self.Add(a));

            removeItems = self.ExceptBy(target.Select(keySelector), keySelector).ToList();
            removeItems.ForEach(r => self.Remove(r));
            return self;
        }
    }
}
